<?php
/**
 * Created by PhpStorm.
 * User: keke
 * Date: 17-11-13
 * Time: 下午1:53
 */

namespace App\Repositories\Absence;

use App\Exceptions\API\APIException;
use App\Exceptions\API\BadRequest;
use App\Models\Absence;

class AbsenceDBRepository implements AbsenceRepository
{
    public function getPaginator(AbsenceFilter $absenceFilter)
    {

        $query = $this->getDBQuery($absenceFilter);

        return $query->paginate($absenceFilter->getPerPage());
    }

    protected function getDBQuery(AbsenceFilter $absenceFilter)
    {
        $AbsenceQuery = Absence::query();
        $AbsenceQuery->with('users.department');

        if ($userId = $absenceFilter->getUserId()) {
            $AbsenceQuery->where('user_id', $userId);
        }

        if ($name = $absenceFilter->getName()) {
            $AbsenceQuery->whereHas('users', function ($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%');
            });
        }

        if ($departmentName = $absenceFilter->getDepartmentName()) {
            $AbsenceQuery->whereHas('users.department', function ($query) use ($departmentName) {
                $query->where('name', 'like', '%' . $departmentName . '%');
            });
        }

        $startTime = $absenceFilter->getStartTime();
        $endTime = $absenceFilter->getEndTime();
        if ($startTime && $endTime) {
            $AbsenceQuery->where('absence_date', '>=', $startTime)
                ->where('absence_date', '<=', $endTime);
        }
        return $AbsenceQuery;
    }
}